<?php
namespace app\shop\controller;

use think\Controller;

class Product extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->ProductModel = model('Product.Product');
        $this->TypeModel = model('Product.Type');
        $this->CartModel = model('Product.Cart');
        $this->BusinessModel = model('Business.Business');
        $this->OrderProductModel = model('Order.Product');
        $this->RelationModel = model('Product.Attribute.Relation');
        $this->AttributeModel = model('Product.Attribute.Attribute');
        $this->CollectionModel = model('Business.Collection');
    }
    // 请求分类列表
    public function type()
    {
        if($this->request->isPost())
        {
            $list = $this->TypeModel->select();

            if($list)
            {
                $this->success('分类列表', null, $list);
                exit;
            }else
            {
                $this->error('暂无分类');
                exit;
            }
        }
    }

    //商品数据列表
    public function index()
    {
        if($this->request->isPost())
        {
            $page = $this->request->param('page', 1, 'trim');
            $typeid = $this->request->param('typeid', 0, 'trim');
            $flag = $this->request->param('flag', '0', 'trim');
            $sort = $this->request->param('sort', 'createtime', 'trim');
            $by = $this->request->param('by', 'desc', 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');
            $limit = 8;

            //偏移量
            $offset = ($page-1)*$limit;

            //查询分类名称
            $TypeName = $this->TypeModel->where(['id' => $typeid])->value('name');
            $TypeName = empty($TypeName) ? '全部分类' : $TypeName;
            
            $where = [];

            //关键词不为空
            if(!empty($keywords))
            {
                $where['name'] = ['like', "%$keywords%"];
            }

            //分类筛选
            if($typeid)
            {
                $where['typeid'] = $typeid;
            }

            //标签筛选
            if($flag != "0")
            {
                $where['flag'] = $flag;
            }

            $list = $this->ProductModel
                ->where($where)
                ->order($sort, $by)
                ->limit($offset, $limit)
                ->select();

            $data = [
                'TypeName' => $TypeName,
                'list' => $list
            ];

            if($list)
            {
                $this->success('返回商品数据', null, $data);
                exit;
            }else
            {
                $this->error('暂无更多商品数据');
                exit;
            }
        }
    }

    //商品详情
    public function info()
    {
        if($this->request->isPost())
        {
            $proid = $this->request->param('proid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $product = $this->ProductModel->with(['type','unit'])->find($proid);

            if(!$product) 
            {
                $this->error('商品不存在');
                exit;
            }

            //判断如果有用户信息就查询是否有收藏过
            $business = $this->BusinessModel->find($busid);

            if($business)
            {
                $where = ['collectid'=>$proid, 'busid' => $busid, 'status'=>'product'];
                $product['collection'] = $this->CollectionModel->where($where)->find() ? true : false;

                //要去找出这个人的购物车数量
                $product['cart'] = $this->CartModel->where(['busid'=>$busid])->sum('nums');
            }else
            {
                //没有登录的话，直接就是未收藏 

                $product['collection'] = false;

                //如果没有登录 购物车的数量 就是0个
                $product['cart'] = 0;
            }

            $comment = $this->OrderProductModel->with(['business'])->where(['proid' => $proid])->select();


            $properties = $sku = $list = [];

            //查找商品规格属性
            $attrid = $this->RelationModel->where(['proid' => $proid])->group('attrid')->column('attrid');
            //$attrid是一个数组结构，在查询时则需要用'IN'并给予一个数组结构进行查询
            $attrs = $this->AttributeModel->where(['id'=> ['IN', $attrid]])->column('id,name');

            if($attrs)
            {
                foreach($attrs as $key=>$item)
                {
                    $properties[$key] = [
                        'k_id' => $key, //属性ID
                        'k' => $item, //规格名称
                        'is_multiple' => false, //是否可多选
                        'v' => []
                    ];
                }
            }

            //查找商品规格列表
            $relationlist = $this->RelationModel->where(['proid' => $proid])->select();

            //重新组装sku的数据结构
            if($properties && $relationlist)
            {
                foreach($relationlist as $item)
                {
                    $properties[$item['attrid']]['v'][] = [
                        'id' => $item['id'],
                        'name' => $item['value'],
                        'price' => (float)bcmul($item['price'], 100), //前端显示的是分单位，浮点数计算，将元化为分  
                        'text_status' => 1,             //属性启用状态
                    ];
                }
            }

            foreach($properties as $item)
            {
                $list[] = [
                    's1' => $item['k_id'],
                    'price' => (float)bcmul($product['price'], 100), //默认的商品价格
                    'stock_num' => $product['stock'],       //默认的商品库存
                ];
            }

            //组装sku
            $sku = [
                'tree' => [],
                'price' => $product['price'], //默认按照单独购买的价格来算
                'stock_num' => $product['stock'], //库存
                'list' => $list
            ];
            
            //返回数据结果
            $data = [
                'product' => $product,
                'comment' => $comment,
                'sku' => $sku, 
                'properties' => $properties,
            ];

            if($product)
            {
                $this->success('返回商品数据', null, $data);
                exit;
            }else
            {
                $this->error('无商品数据');
                exit;
            }
        }
    }

    //商品收藏
    public function collection()
    {
        if($this->request->isAjax())
        {
            $collectid = $this->request->param('collectid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $action = $msg = '';

            //查看商品是否存在
            $product = $this->ProductModel->find($collectid);   
            
            if(!$product)
            {
                $this->error('商品不存在');
                exit;
            }

            //查看登录人信息是否存在
            $business = $this->BusinessModel->find($busid);

            if(!$business)
            {
                $this->error('客户身份未知');
                exit;
            }

            //判断当前用户是否有收藏过该商品
            $where = [
                'busid' => $busid,
                'collectid' => $collectid,
                'status' => 'product'
            ];

            $collect = $this->CollectionModel->where($where)->find();

            if($collect)
            {
                //已收藏过,取消收藏删除
                $result = $this->CollectionModel->where(['id' => $collect['id']])->delete();

                $action = 'delete';
                $msg = '取消收藏';
            }else
            {
                //未收藏 插入语句
                $data = [
                    'collectid' => $collectid,
                    'busid' => $busid, 
                    'status' => 'product'
                ];

                $result = $this->CollectionModel->validate('common/Business/Collection')->save($data);
                $action = 'add';
                $msg = "收藏";
            }

            if($result === FALSE)
            {
                $this->error("{$msg}失败");
                exit;
            }else
            {
                $this->success("{$msg}成功", null, $action);
                //给回去的$action = 'add' 则代表执行的功能是添加
                exit;
            }
        }
    }

    //单独购买
    public function buy()
    {   
        //接收参数
        $busid = $this->request->param('busid', 0, 'trim');
        $proid = $this->request->param('proid', 0, 'trim');
        $nums = $this->request->param('nums', 1, 'trim');
        $relationids = $this->request->param('relationids', "0", 'trim');

        $business = $this->BusinessModel->find($busid);

        if(!$business)
        {
            $this->error('该用户不存在！');
            exit;
        }

        $product = $this->ProductModel->find($proid);

        if(!$product)
        {
            $this->error('商品不存在！');
            exit;
        }

        if($product['stock'] < $nums && $product['stock'] <= 0 )
        {
            $this->error($product['name'] . '库存不足');
            exit;
        }

        //组装数据
        $data = [
            'busid' => $busid,
            'proid' => $proid,
            'nums'  => $nums,
        ];

        //计算
        //根据规格计算商品单价，再计算总价
        if(empty($relationids)) //无规格时
        {
            $data['price'] = $product['price'];
            //将商品的单价'price'和商品选择的数量相乘 bcmul，两个高精度的数字相乘
            $data['total'] = bcmul($product['price'], $nums);
            $data['attrs'] = NULL;
        }else
        {
            //有规格
            $relation = $this->RelationModel->with(['attribute'])->select($relationids);

            $attrs = [];
            $price = $product['price'];

            if($relation)
            {
                foreach($relation as $item)
                {
                    $attrs[] = [
                        'title' => isset($item['attribute']['name']) ? $item['attribute']['name'] : '',
                        'value' => $item['value'],
                        'price' => $item['price']
                    ];

                    $price = bcadd($price, $item['price']);
                }
            }


            $data['price'] = $price;
            $data['total'] = bcmul($price, $nums);
            $data['attrs'] = json_encode($attrs); //转换成JSON的形式
        }
            // 将单独购买的商品插入到购物车表
            // 要增加校验器
            $result = $this->CartModel->validate('common/Product/Cart')->save($data);
        

        if ($result === FALSE) 
        {
            $this->error($this->CartModel->getError());
            exit;
        }
    }

    //查询规格方法
    public function attribute()
    {
        if($this->request->isAjax())
        {
            $relationids = $this->request->param('relationids',0,'trim');

            $relation =  $this->RelationModel->select($relationids);

            if($relation)
            {
                $this->success('有商品规格',null,$relation);
                exit;
            }else
            {
                $this->error('无商品规格');
                exit;
            }
        }
    }
}
